/**
 * ExtDirect4Java
 * @author Maxim Egorov
 * @version 0.1-alpha
 *
 * Copyright(c) 2009, Swissdotnet S?rl
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */
package ch.swissdotnet.extdirect4j;

import java.lang.reflect.Method;

public class AnnotatedAction extends AbstractAction {

    public AnnotatedAction(final Object instance) {
        super(instance);
        this.constructByAnnotation(this.getClazz());
    }

    public AnnotatedAction(final Class clazz) {
        super(clazz);
        this.constructByAnnotation(clazz);
    }

    public AnnotatedAction(final String className) {
        super(className);
        this.constructByAnnotation(Utils.getClassByName(className));
    }

    @SuppressWarnings("unchecked")
    private void constructByAnnotation(final Class clazz) {
        final String remoteName;
//        final boolean lazyInit;
        ExtRemoteAction annotation = (ExtRemoteAction) clazz.getAnnotation(ExtRemoteAction.class);
        if (annotation != null) {
            remoteName = annotation.name();
//            lazyInit = annotation.lazyInit();
        } else {
            remoteName = clazz.getName();
//            lazyInit = false;
        }
        this.setRemoteName(remoteName);
        //todo lazyInit, inherit
//        this.construct();
//        this.construct(remoteName != null ? remoteName : clazz.getName(), clazz, lazyInit);
    }

    void beforeApply() {
        MethodResolver resolver = new MethodResolver() {
            ExtDirectMethod resolve(Method method) {
                ExtRemoteMethod annotation = method.getAnnotation(ExtRemoteMethod.class);
                if (annotation != null) {
                    final String remoteName = annotation.name();
                    if ("".equals(remoteName)) {
                        return new ExtDirectMethod(method);
                    } else {
                        return new ExtDirectMethod(remoteName, method);
                    }

                } else {
                    return null;
                }
            }
        };
        this.applyMethodsRecursively(this.getClazz(), resolver);
    }
}
